package it.wyx.kafkaclients.consumer.offset;

import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

/**
 * 指定offset消费
 * @author wyx
 * @version V 1
 * @Date 2022/10/30
 */
public class CustomConsumerSeek {
	private static final String BROKER_LIST = "localhost:9092";
	private static final String TOPIC = "test-topic";
	private static final String GROUP_ID = "test-group";

	public static void main(String[] args) {
		Properties properties = new Properties();
		properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BROKER_LIST);
		properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
		properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
		properties.put(ConsumerConfig.GROUP_ID_CONFIG, GROUP_ID);

		KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);

		consumer.subscribe(Collections.singletonList(TOPIC));

		Set<TopicPartition> assignment= new HashSet<>();
		// 保证分区分配方案已经制定完成
		while (assignment.size() == 0) {
			consumer.poll(Duration.ofSeconds(1));
			// 获取消费者分区分配信息(有了分区分配信息才能开始消费)
			assignment = consumer.assignment();
		}
		// 遍历所有分区，并指定 offset 从 1700 的位置开始消费
		for (TopicPartition tp: assignment) {
			consumer.seek(tp, 1700);
		}

		while (true) {
			ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
			System.out.println("接收消费records");
			for (ConsumerRecord<String, String> record : records) {
				System.out.println(record);
			}
		}
	}
}
